import { defineStore } from 'pinia';

interface Task {
    id: number;
    path: string;
    remindType: 'voice'|'vibrate' | 'voiceAndVibrate';
    times?: number;
    execute?: () => Promise<void>;
}

export const useVoiceTaskStore = defineStore('voiceTask', {
    state: (): { ids: number[], queue: Task[], status: number } => ({
        ids: [],
        queue: [],
        status: 0, // 0-未执行 1-执行中 2-已暂停
    }),
    actions: {
        stopVoiceTask(): void {
            console.log("VoiceTask，停止任务，剩余任务:", this.queue.length);
            this.status = 2;
        },
        async startVoiceTask(): Promise<void> {
            console.log("VoiceTask，启动任务，剩余任务:", this.queue.length);
            this.status = 0;
            await this.runVoiceTask();
        },
        async play(task: Task): Promise<void> {
            console.log(`开始播放111: ${task.id}`);
            const times = task.times ? task.times : 1;
            let player: PlusAudio | null = null;
            for (let i = 0; i < times; i++) {
                console.log(`开始播放222: ${task.id}`);
                await this.runPlayTask(task, player);
            }
        },
        addVoiceTask(task: Task): void {
            if (this.ids.includes(task.id)) {
                console.log("VoiceTask，任务正在执行中，加入队列失败，id:" + task.id);
                return;
            }
            console.log("VoiceTask，任务加入队，task:", task);
            const times = task.times ? task.times : 1;
            for (let i = 0; i < times; i++) {
                task.execute = () => new Promise((resolve, reject) => {
                    if( ['vibrate','voiceAndVibrate'].includes(task.remindType) ) {
                        uni.vibrateLong({
                            success: (res) => {
                                console.log("VoiceTask，执行振动成功，task，res:", task,res);
                            },
                            fail: (res) => {
                                console.error("VoiceTask，执行振动失败，task，res:", task,res);
                            },
                            complete: () => {
                                if('vibrate' == task.remindType){
                                    setTimeout(() => {
                                        resolve();
                                    },1000)
                                }
                            }
                        })
                    }
                    if( ['voice','voiceAndVibrate'].includes(task.remindType) ) {
                        console.log(`播放开始: ${task.id}，路径：${task.path}`);
                        // 路径格式：目录 + 风格 + 文件名
                        let player = plus.audio.createPlayer(task.path);
                        player.play(() => {
                            console.log(`播放完成: ${task.id}`);
                            player.close();
                            resolve();
                        });
                    }
                });
                this.ids.push(task.id);
                this.queue.push(task);
                console.log("VoiceTask，任务加入队列成功，id:" + task.id);
                if (this.status === 0) {
                    this.runVoiceTask();
                }
            }
        },
        async runVoiceTask(): Promise<void> {
            this.status = 1;
            while (this.status === 1 && this.queue.length > 0) {
                let index = -1;
                try {
                    const task = this.queue.shift();
                    console.log("VoiceTask，任务开始执行，id:" + task?.id);
                    if(task){
                        await task.execute();
                        index = this.ids.indexOf(task.id);
                        console.log("VoiceTask，任务执行完成，id:" + task.id);
                    }
                } catch (e) {
                    console.error("VoiceTask:runVoiceTask，任务执行出现异常", e);
                } finally {
                    if (index !== -1) {
                        this.ids.splice(index, 1); // 删除元素
                    }
                    continue; // xiaoch 此行不要去掉，否则下一个任务不会继续执行
                }
            }
            this.status = 0;
        },
        async runPlayTask(task: Task, player: PlusAudioAudioPlayer | null): Promise<void> {
            return new Promise((resolve, reject) => {
                try {
                    if (player) {
                        player.stop();
                    }
                    console.log(`开始播放: ${task.id}，文件路径：${task.path}`);
                    player = plus.audio.createPlayer(task.path);
                    player.play(() => {
                        console.log(`播放完成: ${task.id}`);
                        resolve();
                    });
                    player.addEventListener('error',(result) => {
                        console.error(`播放出错: ${task.id}`, result);
                        reject();
                    })
                } catch (e) {
                    console.error("VoiceTask play，任务执行出现异常", e);
                }
            });
        }
    }
});

export default useVoiceTaskStore;